package com.netty.rpc.client;

import com.netty.rpc.encode.Decode;
import com.netty.rpc.encode.Encode;
import com.netty.rpc.resp.CalcResponse;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.concurrent.CompletableFuture;

public final class NettyClient {

    private final Bootstrap bootstrap;


    public NettyClient(NettyClientHandler nettyClientHandler){
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        try{
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new Decode(CalcResponse.class));
                        //ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(nettyClientHandler);
                        ch.pipeline().addLast(new Encode());
                    }
                });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Channel doConnect() {
        try {
            CompletableFuture<Channel> completableFuture = new CompletableFuture<>();
            bootstrap.connect("192.168.128.228", 8081).addListener((ChannelFutureListener)future -> {
                if(future.isSuccess()){
                    completableFuture.complete(future.channel());
                }else{
                    System.out.println("netty client connect fail...");
                }
            });
            return completableFuture.get();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
